<template>
  <div class="item-list-container">
    <!-- 搜索、筛选和视图切换区域 -->
    <n-card class="filter-section" size="small">
      <unified-filter-bar
        :categories="categories"
        :filters="filters"
        :loading="categoriesLoading"
        :view-mode="viewMode"
        @update-filters="handleUpdateFilters"
        @update-sort="handleSortChange"
        @update-view-mode="handleViewModeChange"
        @search="handleSearch"
      />
    </n-card>

    <!-- 物品列表结果区域 -->
    <n-card class="items-result-section" size="small">
      <!-- 结果统计信息 -->
      <div class="result-info">
        <n-text :depth="3" v-if="!loading">
          共 {{ total }} 个物品，第 {{ filters.page }}/{{ Math.ceil(total / filters.pageSize) }} 页
        </n-text>
      </div>

      <!-- 卡片视图 -->
      <div v-if="viewMode === 'card'" class="card-view">
        <!-- 加载状态 - 使用骨架屏 -->
        <div v-if="loading" class="skeleton-grid">
          <n-grid
            cols="1 s:2 m:3 l:4 xl:5 2xl:6"
            :x-gap="16"
            :y-gap="16"
            responsive="screen"
          >
            <n-grid-item v-for="i in pageSize" :key="`skeleton-${i}`">
              <loading-skeleton type="card" />
            </n-grid-item>
          </n-grid>
        </div>

        <!-- 实际内容 -->
        <div v-else-if="items.length > 0">
          <n-grid
            cols="1 s:2 m:3 l:4 xl:5 2xl:6"
            :x-gap="16"
            :y-gap="16"
            responsive="screen"
          >
            <n-grid-item v-for="item in items" :key="item.object_id">
              <item-card
                :item="item"
                @search-name="handleSearchByName"
                @show-detail="handleShowDetail"
              />
            </n-grid-item>
          </n-grid>
        </div>

        <!-- 空状态 -->
        <n-empty
          v-else
          description="没有找到符合条件的物品"
        />
      </div>

      <!-- 表格视图 -->
      <div v-else-if="viewMode === 'table'" class="table-view">
        <item-table
          :items="items"
          :loading="loading"
          @row-click="handleItemClick"
        />
      </div>

      <!-- 分页 -->
      <n-space justify="center" class="pagination">
        <n-pagination
          v-model:page="currentPage"
          v-model:page-size="pageSize"
          :item-count="total"
          :page-sizes="[20, 50, 100]"
          show-size-picker
          @update:page="handlePageChange"
          @update:page-size="handlePageSizeChange"
        />
      </n-space>
    </n-card>

    <!-- 物品详情弹窗 -->
    <item-detail-modal
    class="item-detail-modal"
      v-model:show="showDetailModal"
      :object-id="selectedItemId"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, watch, nextTick, onUnmounted } from 'vue'
import { debounce } from 'lodash-es'
import { useItemsStore } from '@/stores/items'
import type { ItemsFilter, Item } from '@/types/items'
import UnifiedFilterBar from './components/UnifiedFilterBar.vue'
import ItemCard from './components/ItemCard.vue'
import ItemTable from './components/ItemTable.vue'
import ItemDetailModal from '@/components/ItemDetailModal.vue'
import LoadingSkeleton from '@/components/common/LoadingSkeleton.vue'


// 引入样式
import '@/styles/components/itemlist/ItemList.css'

// 状态管理
const itemsStore = useItemsStore()

// 计算属性
const items = computed(() => itemsStore.items)
const total = computed(() => itemsStore.total)
const loading = computed(() => itemsStore.loading)
const categories = computed(() => itemsStore.categories)
const categoriesLoading = computed(() => itemsStore.categoriesLoading)
const filters = computed(() => itemsStore.filters)
const viewMode = computed(() => itemsStore.viewMode)

// 本地状态
const currentPage = ref(filters.value.page)
const pageSize = ref(filters.value.pageSize)
const showDetailModal = ref(false)
const selectedItemId = ref<number | null>(null)

// 生命周期钩子 - 优化初始化顺序
onMounted(async () => {
  // 第一优先级：立即加载物品列表（用户最关心的内容）
  if (filters.value.sort === 'default') {
    // 直接更新筛选条件，这会自动触发fetchItems()
    handleSortChange('price_desc')
  } else {
    // 如果已经有排序条件，直接加载物品列表
    itemsStore.fetchItems()
  }

  // 第二优先级：延迟加载分类数据（非关键路径）
  // 使用 nextTick 确保物品列表请求先发出
  await nextTick()
  setTimeout(() => {
    itemsStore.fetchCategories()
  }, 100) // 延迟100ms，让物品列表请求优先处理
})

// 监听筛选条件变化
watch(
  () => filters.value,
  (newFilters) => {
    currentPage.value = newFilters.page
    pageSize.value = newFilters.pageSize
  },
  { deep: true }
)

// 搜索处理 - 使用防抖
const handleSearch = debounce((value: string) => {
  itemsStore.updateFilters({ search: value })
}, 500)

// 按名称搜索
const handleSearchByName = (name: string) => {
  itemsStore.updateFilters({ search: name })
}

// 视图模式切换
const handleViewModeChange = (mode: 'card' | 'table') => {
  itemsStore.setViewMode(mode)
}

// 排序变更
const handleSortChange = (value: string) => {
  itemsStore.updateFilters({ sort: value })
}

// 分页处理
const handlePageChange = (page: number) => {
  itemsStore.updateFilters({ page })
}

const handlePageSizeChange = (pageSize: number) => {
  itemsStore.updateFilters({ pageSize })
}

// 筛选条件更新
const handleUpdateFilters = (newFilters: Partial<ItemsFilter>) => {
  itemsStore.updateFilters(newFilters)
}

// 点击物品 - 改为显示弹窗
const handleItemClick = (item: Item) => {
  selectedItemId.value = item.object_id
  showDetailModal.value = true
}

// 显示物品详情弹窗
const handleShowDetail = (objectId: number) => {
  selectedItemId.value = objectId
  showDetailModal.value = true
}
</script>

